home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / CPTUTT22.ZIP / CHAP09.TXT < prev    next >
Text File  |  1992-01-20  |  23KB  |  531 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.                                                         Chapter 9
  8.                        MULTIPLE INHERITANCE AND FUTURE DIRECTIONS
  9.  
  10. C++ version 2.0 was released by AT&T during the summer of 1989, and
  11. the major addition to the language is multiple inheritance, the
  12. ability to inherit data and methods from more than one class into
  13. a subclass.  Multiple inheritance and a few of the other additions
  14. to the language will be discussed in this chapter along with some
  15. of the expected future directions of the language.
  16.  
  17. Several companies have C++ compilers available in the marketplace,
  18. and many others are sure to follow.  Because the example programs
  19. in this tutorial are designed to be as generic as possible, most
  20. should be compilable with any good quality C++ compiler provided
  21. it follows the AT&T definition of version 2.1 or newer.  Many of
  22. these examples will not work with earlier definitions because the
  23. language was significantly changed with the version 2.1 update.
  24.  
  25. After completing this tutorial, you should have enough experience
  26. with the language to study additional new constructs on your own
  27. as they are implemented by the various compiler writers.  We will
  28. update the entire tutorial as soon as practical following
  29. procurement of any new compiler, but hopefully the language will
  30. not change rapidly enough now to warrant an update oftener than
  31. annually.  Please feel free to contact us for information on
  32. updates to the Coronado Enterprises C++ tutorial.
  33.  
  34.  
  35. MULTIPLE INHERITANCE
  36. _________________________________________________________________
  37.  
  38. A major recent addition to the C++ language is the ability to
  39. inherit methods and variables from two or more parent classes when
  40. building a new class.  This is called multiple inheritance, and is
  41. purported by many people to be a major requirement for an object
  42. oriented programming language.  Some writers, however, have
  43. expressed doubts as to the utility of multiple inheritance.  To
  44. illustrate the validity of this, it was not easy to think up a good
  45. example of the use of multiple inheritance as an illustration for
  46. this chapter.  In fact, the resulting example is sort of a forced
  47. example that really does nothing useful.  It does however,
  48. illustrate the mechanics of the use of multiple inheritance with
  49. C++, and that is our primary concern at this time.
  50.  
  51. The biggest problem with multiple inheritance involves the
  52. inheritance of variables or methods from two or more parent classes
  53. with the same name.  Which variable or method should be chosen as
  54. the inherited variable or method if two or more have the same name?
  55. This will be illustrated in the next few example programs.
  56.  
  57.  
  58.                                                          Page 9-1
  59.  
  60.            Chapter 9 - Multiple Inheritance and Future Directions
  61.  
  62.  
  63. SIMPLE MULTIPLE INHERITANCE
  64. _________________________________________________________________
  65.  
  66. An examination of the file named MULTINH1.CPP    ================
  67. will reveal the definition of two very simple      MULTINH1.CPP
  68. classes in lines 4 through 27 named moving_van   ================
  69. and driver.
  70.  
  71. In order to keep the program as simple as possible, all of the
  72. member methods are defined as inline functions.  This puts the code
  73. for the methods where it is easy to find and study.  You will also
  74. notice that all variables in both classes are declared to be
  75. protected so they will be readily available for use in any class
  76. which inherits them.  The code for each class is kept very simple
  77. so that we can concentrate on studying the interface to the methods
  78. rather than spending time trying to understand complex methods.
  79. As mentioned previously, chapter 12 will illustrate the use of non-
  80. trivial methods.
  81.  
  82. In line 30, we define another class named driven_truck which
  83. inherits all of the data and all of the methods from both of the
  84. previously defined classes.  In the last two chapters, we studied
  85. how to inherit a single class into another class, and to inherit
  86. two or more classes, the same technique is used except that we use
  87. a list of inherited classes separated by commas as illustrated in
  88. line 30.  The observant student will notice that we use the keyword
  89. public prior to the name of each inherited class in order to be
  90. able to freely use the methods within the subclass.  In this case,
  91. we didn't define any new variables, but we did introduce two new
  92. methods into the subclass in lines 32 through 39.
  93.  
  94. We declared an object named chuck_ford which presumably refers to
  95. someone named Chuck who is driving a Ford moving van.  The object
  96. named chuck_ford is composed of four variables, three from the
  97. moving_van class, and one from the driver class.  Any of these four
  98. variables can be manipulated in any of the methods defined within
  99. the driven_truck class in the same way as in a singly inherited
  100. situation.  A few examples are given in lines 47 through 56 of the
  101. main program and the diligent student should be able to add
  102. additional output messages to this program if he understands the
  103. principles involved.
  104.  
  105. All of the rules for private or protected variables and public or
  106. private method inheritance as used with single inheritance extends
  107. to multiple inheritance.
  108.  
  109.  
  110. DUPLICATED METHOD NAMES
  111. _________________________________________________________________
  112.  
  113. You will notice that both of the parent classes have a method named
  114. initialize(), and both of these are inherited into the subclass
  115. with no difficulty.  However, if we attempt to send a message to
  116.  
  117.                                                          Page 9-2
  118.  
  119.            Chapter 9 - Multiple Inheritance and Future Directions
  120.  
  121. one of these methods, we will have a problem, because the system
  122. does not know which we are referring to.  This problem will be
  123. solved and illustrated in the next example program.
  124.  
  125. Before going on to the next example program, it should be noted
  126. that we have not declared any objects of the two parent classes in
  127. the main program.  Since the two parent classes are simply normal
  128. classes themselves, it should be apparent that there is nothing
  129. magic about them and they can be used to define and manipulate
  130. objects in the usual fashion.  You may wish to do this to review
  131. your knowledge of simple classes and objects of those classes.
  132.  
  133. Be sure to compile and execute this program after you understand
  134. its operation completely.
  135.  
  136.  
  137.  
  138. MORE DUPLICATE METHOD NAMES
  139. _________________________________________________________________
  140.  
  141. The second example program in this chapter named ================
  142. MULTINH2.CPP, illustrates the use of classes       MULTINH2.CPP
  143. with duplicate method names being inherited into ================
  144. a derived class.
  145.  
  146. If you study the code, you will find that a new method has been
  147. added to all three of the classes named cost_per_full_day().  This
  148. was done intentionally to illustrate how the same method name can
  149. be used in all three classes.  The class definitions are no problem
  150. at all, the methods are simply named and defined as shown.  The
  151. problem comes when we wish to use one of the methods since they are
  152. all the same name and they have the same numbers and types of
  153. parameters and identical return types.  This prevents some sort of
  154. an overloading rule to disambiguate the message sent to one or more
  155. of the methods.
  156.  
  157. The method used to disambiguate the method calls are illustrated
  158. in lines 60, 64, and 68 of the main program.  The solution is to
  159. prepend the class name to the method name with the double colon as
  160. used in the method implementation definition.  This is referred to
  161. as qualifying the method name.  Qualification is not necessary in
  162. line 68 since it is the method in the derived class and it will
  163. take precedence over the other method names.  Actually, you could
  164. qualify all method calls, but if the names are unique, the compiler
  165. can do it for you and make your code easier to write and read.
  166.  
  167. Be sure to compile and execute this program and study the results.
  168. The observant student will notice that there is a slight
  169. discrepancy in the results given in lines 79 through 81, since the
  170. first two values do not add up to the third value exactly.  This
  171. is due to the limited precision of the float variable but should
  172. cause no real problem.
  173.  
  174.  
  175.  
  176.                                                          Page 9-3
  177.  
  178.            Chapter 9 - Multiple Inheritance and Future Directions
  179.  
  180.  
  181. DUPLICATED VARIABLE NAMES
  182. _________________________________________________________________
  183.  
  184. If you will examine the example program named    ================
  185. MULTINH3.CPP, you will notice that each base       MULTINH3.CPP
  186. class has a variable with the same name.         ================
  187.  
  188. According to the rules of inheritance, an object
  189. of the driven_truck class will have two variables with the same
  190. name, weight.  This would be a problem if it weren't for the fact
  191. that C++ has defined a method of accessing each one in a well
  192. defined way.  You have probably guessed that we will use
  193. qualification to access each variable.  Lines 38 and 45 illustrate
  194. the use of the variables.  It may be obvious, but it should be
  195. explicitly stated, that there is no reason that the subclass itself
  196. cannot have a variable of the same name as those inherited from the
  197. parent classes.  In order to access it, no qualification would be
  198. required.
  199.  
  200. It should be apparent to you that once you understand single
  201. inheritance, multiple inheritance is nothing more than an extension
  202. of the same rules.  Of course, if you inherit two methods or
  203. variables of the same name, you must use qualification to allow the
  204. compiler to select the correct one.
  205.  
  206.  
  207. PRACTICAL MULTIPLE INHERITANCE
  208. _________________________________________________________________
  209.  
  210. Examine the example program named DATETIME.H     ================
  211. for a practical example using multiple              DATETIME.H
  212. inheritance.  You will notice that we are        ================
  213. returning to our familiar date and time classes
  214. from earlier chapters.
  215.  
  216. There is a good deal to be learned from this very short header file
  217. since it is our first example of member initialization.  There are
  218. two constructors for this class, the first being a very simple
  219. constructor that does nothing in itself as is evident from an
  220. examination of line 12.  This constuctor allows the constructors
  221. to be executed for the classes new_date and time_of_day.  In both
  222. cases a constructor will be executed that requires no parameters,
  223. and such a constructor is available for each of these two classes.
  224.  
  225. The second constuctor is more interesting since it does not simply
  226. use the default constructor, but instead passes some of the input
  227. parameters to the inherited class constructors.  Following the
  228. colon in line 13 are two member initializers which are used to
  229. initialize members of this class.  Since the two parent classes are
  230. inherited, they are also members of this class and can be
  231. initialized as shown.  Each of the member initializers is actually
  232. a call to a constructor of the parent classes and it should be
  233. evident that there must be a constructor with the proper number of
  234.  
  235.                                                          Page 9-4
  236.  
  237.            Chapter 9 - Multiple Inheritance and Future Directions
  238.  
  239. input parameters to respond to the messages given.  You will note
  240. that in line 14, we are actually calling the constructor with no
  241. parameters given explicitly.  If we chose, we could simply let the
  242. system call that constructor automatically, but this gives us an
  243. explicit comment on what is happening.
  244.  
  245.  
  246. MORE ABOUT MEMBER INITIALIZERS
  247. _________________________________________________________________
  248.  
  249. Actually, we can use the member initializer to initialize class
  250. members also.  If we had a class member of type int named
  251. member_var, we could initialize it also by mentioning the name of
  252. the member followed by the value we desired to initialize it to in
  253. parentheses.  If we wished to initialize it to the value 13, we
  254. could use the following line of code in the member initializer
  255. list;
  256.  
  257.    member_var(13);
  258.  
  259. Following all member initialization, the normal constructor code
  260. is executed which in this case is given in line 16.
  261.  
  262.  
  263. ORDER OF MEMBER INITIALIZATION
  264. _________________________________________________________________
  265.  
  266. The order of member initialization may seem a bit strange, but it
  267. does follow a few simple rules.  The order of member initialization
  268. does not follow the order given by the initialization list, but
  269. another very strict order over which you have complete control.
  270. All inherited classes are initialized first in the order they are
  271. listed in the class header.  If lines 14 and 15 were reversed,
  272. class new_date would still be initialized first because it is
  273. mentioned first in line 8.  It has been mentioned that C++ respects
  274. its elders and initializes its parents prior to itself.  That
  275. should be a useful memory aid in the use of member initializers.
  276.  
  277. Next, all local class members are initialized in the order in which
  278. they are declared in the class, not the order in which they are
  279. declared in the initialization list.  Actually, it would probably
  280. be good practice to not use the member initializer to initialize
  281. class members but instead to initialize them in the normal
  282. constructor code.
  283.  
  284. Finally, after the member initializers are all executed in the
  285. proper order, the main body of the constructor is executed in the
  286. normal manner.
  287.  
  288. USING THE NEW CLASS
  289. _________________________________________________________________
  290.  
  291. The example program named USEDTTM.CPP uses the datetime class we
  292. just built, and like our previous examples, the main program is
  293.  
  294.                                                          Page 9-5
  295.  
  296.            Chapter 9 - Multiple Inheritance and Future Directions
  297.  
  298. kept very simple and straight forward.  You will  ===============
  299. note that the default constructor is used for       USEDTTM.CPP
  300. the object named now, and the constructor with    ===============
  301. the member initializers is used with the objects
  302. named birthday and special.
  303.  
  304. The diligent student should have no trouble understanding the
  305. remaining code in this example.
  306.  
  307.  
  308. FUTURE DIRECTIONS OF C++
  309. _________________________________________________________________
  310.  
  311. An ANSI committee has been formed to write an ANSI standard for
  312. C++.  They first met in the Spring of 1990 and are expected to
  313. complete the standard in about three years.  Until the new standard
  314. is released, the C++ language is expected to stay fairly stable.
  315. However, due to the nature of compiler writers and their desire to
  316. slightly improve their offerings over their competitors, you can
  317. bet that the language will not remain static during this three year
  318. period.
  319.  
  320. Many small changes have been added during the past year that barely
  321. affect the casual programmer, or even the heavy user of the
  322. language.  You can be sure that the language will evolve slowly and
  323. surely into a very usable and reliable language.  There are two
  324. areas, however, that should be discussed in a little detail because
  325. they will add so much to the language in future years.  Those two
  326. topics are parameterized types and exception handling.
  327.  
  328.  
  329.  
  330. FUTURE DIRECTIONS - PARAMETERIZED TYPES
  331. _________________________________________________________________
  332.  
  333. Many times, when developing a program, you wish to perform some
  334. operation on more than one data type.  For example you may wish to
  335. sort a list of integers, another list of floating point numbers,
  336. and a list of alphabetic strings.  It seems silly to have to write
  337. a separate sort function for each of the three types when all three
  338. are sorted in the same logical way.  With parameterized types, you
  339. will be able to write a single sort routine that is capable of
  340. sorting all three of the lists.
  341.  
  342. This is already available in the Ada language as the generic
  343. package or procedure.  Because it is available in Ada, there is a
  344. software components industry that provides programmers with
  345. prewritten and thoroughly debugged software routines that work with
  346. many different types.  When this is generally available in C++,
  347. there will be a components industry for C++ and precoded, debugged
  348. and efficient source code will be available off the shelf to
  349. perform many of the standard operations.  These operations will
  350. include such things as sorts, queues, stacks, lists, etc.
  351.  
  352.  
  353.                                                          Page 9-6
  354.  
  355.            Chapter 9 - Multiple Inheritance and Future Directions
  356.  
  357.  
  358. Bjarne Stroustrup has announced that parameterized types, otherwise
  359. known as templates or generics, will be available in a future
  360. version of C++.  He has presented a paper with details of one way
  361. to implement them, but this is only a suggestion, not a
  362. specification.
  363.  
  364. Borland International has included templates in version 3.0 of
  365. Borland C++, and hopefully their implementation will be very close
  366. to the final definition of templates.
  367. The next three example programs will illustrate the use of
  368. templates with Borland's compiler, but may not work with other
  369. compilers.
  370.  
  371.  
  372. THE FIRST TEMPLATE
  373. _________________________________________________________________
  374.  
  375. The example program named TEMPLAT1.CPP is the    ================
  376. first example of the use of a template.  This      TEMPLAT1.CPP
  377. program is so simple it seems silly to even      ================
  378. bother with it but it will illustrate the use of
  379. the parameterized type.
  380.  
  381. The template is given in lines 4 through 8 with the first line
  382. indicating that it is a template with a single type to be replaced,
  383. the type ANY_TYPE.  This type can be replaced by any type which can
  384. be used in the comparison operation in line 7.  If you have defined
  385. a class, and you have overloaded the operator ">", then this
  386. template can be used with objects of your class.  Thus, you do not
  387. have to write a maximum function for each type or class in your
  388. program.
  389.  
  390. This function is included automatically for each type it is called
  391. with in the program, and the code itself should be very easy to
  392. understand.
  393.  
  394. The diligent student should realize that nearly the same effect can
  395. be achieved through use of a macro, except that when a macro is
  396. used, the strict type checking is not done.  Because of this and
  397. because of the availability of the inline method capability in C++,
  398. the use of macros is essentially non-existent by experienced C++
  399. programmers.
  400.  
  401.  
  402.  
  403. A CLASS TEMPLATE
  404. _________________________________________________________________
  405.  
  406. The example program named TEMPLAT2.CPP is a      ================
  407. little more involved since it provides a           TEMPLAT2.CPP
  408. template for an entire class rather than a       ================
  409. single function.  The template code is given in
  410. lines 6 through 16 and a little study will show
  411.  
  412.                                                          Page 9-7
  413.  
  414.            Chapter 9 - Multiple Inheritance and Future Directions
  415.  
  416. that this is an entire class definition.  The diligent student will
  417. recognize that this is a very weak stack class since there is
  418. nothing to prevent popping data from an empty stack, and there is
  419. no indication of a full stack.  Our intent, however, is to
  420. illustrate the use of the parameterized type and to do so using the
  421. simplest class possible.
  422.  
  423. In the main program we create an object named int_stack in line 25
  424. which will be a stack designed to store integers, and another
  425. object named float_stack in line 26 which is designed to store
  426. float type values.  In both cases, we enclose the type we desire
  427. this object to work with in "<>" brackets, and the system creates
  428. the object by first replacing all instances of ANY_TYPE with the
  429. desired type, then creating the object of that type.  You will note
  430. that any type can be used that has an assignment capability since
  431. lines 13 and 14 use the assignment operator on the parameterized
  432. type.
  433.  
  434. Even though the strings are all of differing lengths, we can even
  435. use the stack to store a stack of strings if we only store a
  436. pointer to the strings and not the entire string.  This is
  437. illustrated in the object named string_stack declared in line 27
  438. and used later in the program.
  439.  
  440. This program should be fairly easy for you to follow if you spend
  441. a bit of time studying it.  You should compile and run it if you
  442. have a compiler that will handle this new construct.
  443.  
  444.  
  445.  
  446. REUSING THE STACK CLASS
  447. _________________________________________________________________
  448.  
  449. The program named TEMPLAT3.CPP uses the same     ================
  450. class with the template as defined in the last     TEMPLAT3.CPP
  451. program but in this case, it uses the date class ================
  452. developed earlier as the stack members.  More
  453. specifically, it uses a pointer to the date
  454. class as the stack member.
  455.  
  456. Because class assignment is legal, you could also store the actual
  457. class in the stack rather than just the pointer to it.  To do so
  458. however, would be very inefficient since the entire class would be
  459. copied into the stack each time it is pushed and the entire class
  460. would be copied out again when it was popped.  Use of the pointer
  461. is a little more general, so it was illustrated here for your
  462. benefit.
  463.  
  464. All three of the previous programs can be compiled and executed if
  465. you have a copy of Borland C++ version 3.0.  Other compilers may
  466. not work with these programs since parameterized types are not yet
  467. a part of the C++ specification.
  468.  
  469.  
  470.  
  471.                                                          Page 9-8
  472.  
  473.            Chapter 9 - Multiple Inheritance and Future Directions
  474.  
  475.  
  476. FUTURE DIRECTIONS - EXCEPTION HANDLING
  477. _________________________________________________________________
  478.  
  479. A future version of C++ will have some form of exception handling
  480. to allow the programmer to trap errors and prevent the system from
  481. completely shutting down when a fatal error occurs.  The Ada
  482. language allows the programmer to trap any error that occurs, even
  483. system errors, execute some recovery code, and continue on with the
  484. program execution in a very well defined way.  Bjarne Stroustrup,
  485. working in conjunction with the ANSI-C++ committee, has announced
  486. that some form of exception handling will be implemented but he has
  487. not stated what form it would take as of this writing.
  488.  
  489.  
  490. WHAT SHOULD BE YOUR NEXT STEP?
  491. _________________________________________________________________
  492.  
  493. Once again, we have reached a major milestone in C++ programming.
  494. With the ability to use inheritance, you have nearly all of the
  495. tools you need to effectively use the object oriented programming
  496. techniques of C++ and you would do well to stop studying again and
  497. begin programming.  The only topic left with C++ is virtual methods
  498. which are used for dynamic binding or polymorphism.  This will be
  499. covered in the next two chapters.  The vast majority of all
  500. programming can be done without dynamic binding, and in attempting
  501. to force it into every program, you could wind up with an
  502. unreadable mess, so you should approach it slowly.
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.  
  530.                                                          Page 9-9
  531.